package io.qifan.desktop.client.state;

import io.qifan.desktop.api.protocol.request.ConnectReqMsg;
import io.qifan.desktop.client.event.Events;
import io.qifan.desktop.client.socket.SocketUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.messaging.simp.stomp.StompFrameHandler;
import org.springframework.messaging.simp.stomp.StompHeaders;
import org.springframework.stereotype.Component;

import java.lang.reflect.Type;
import java.util.Map;

@Component
@Slf4j
public class StateMachine {
    @Autowired
    Map<String, OrderState> orderStateMap;
    String currentState = OrderState.OFFLINE;

    @EventListener(Events.OnlineEvent.class)
    public void changeStateToOnline() {
        currentState = OrderState.ONLINE;
    }

    @EventListener(Events.OfflineEvent.class)
    public void changeStateToOffline() {
        currentState = OrderState.OFFLINE;
    }

    @EventListener(Events.SendConnectEvent.class)
    public void sendConnectMsg(Events.SendConnectEvent sendConnectEvent) {
        log.debug("当前状态: {}", currentState);
        orderStateMap.get(currentState).sendConnection(sendConnectEvent.getConnectMessage());
    }

    @EventListener(Events.OnlineEvent.class)
    public void receiveConnection() {
        SocketUtils.stompSession.subscribe("/user/topic/desktop/connect/request", new StompFrameHandler() {
            @Override
            public Type getPayloadType(StompHeaders headers) {
                return ConnectReqMsg.class;
            }

            @Override
            public void handleFrame(StompHeaders headers, Object payload) {
                orderStateMap.get(currentState).receiveConnection((ConnectReqMsg) payload);
            }
        });
    }
}
